package com.gupao.template.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public abstract class JdbcTemplate {
    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public List<?> executeQuery(String sql, Object[] values, RowMapper<?> rowMapper){
        try {
            //1、获取连接
            Connection connection = dataSource.getConnection();
            //2、创建语句集
            PreparedStatement ps = connection.prepareStatement(sql);
            //3、执行语句集
            ResultSet rs = this.executeQuery(ps,values);
            //4、处理结果集
            List<?> result = this.paresResultSet(rs, rowMapper);
            //5、关闭结果集
            rs.close();
            //6、关闭语句集
            ps.close();
            //7、关闭连接
            connection.close();
            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected ResultSet executeQuery(PreparedStatement ps, Object[] values) throws Exception {
        for (int i = 0; i < values.length; i++) {
            ps.setObject(i,values[i]);
        }
        return ps.executeQuery();
    }

    protected List<?> paresResultSet(ResultSet rs, RowMapper<?> rowMapper) throws Exception {
        List<Object> result = new ArrayList<Object>();
        int rowNum = 1;
        while (rs.next()){
            result.add(rowMapper.mapRow(rs,rowNum ++));
        }
        return result;
    }
}
